package com.bydq.patrolsystem.aop;


import com.bydq.patrolsystem.annotation.MyLog;
import com.bydq.patrolsystem.entity.PsLogs;
import com.bydq.patrolsystem.entity.PsUser;
import com.bydq.patrolsystem.service.PsLogsService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Aspect
@Component
public class WebLogAspect {

    @Autowired
    public PsLogsService psLogsService;

    @Pointcut("@annotation(com.bydq.patrolsystem.annotation.MyLog)")
    public void controller(){}

    @Around("controller()&&@annotation(log)")
    public Object introcepter(ProceedingJoinPoint pjp, MyLog log) throws Throwable{
        Object result = null;
        //获取session和用户
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpSession session  = attr.getRequest().getSession(true);
        PsUser user = null;
        try {
             result = pjp.proceed();

             user =  (PsUser)session.getAttribute("user");
             //插入日志
            PsLogs psLogs = null;
            if(user != null){
                psLogs = new PsLogs(user.getUserCode(), user.getUserName(), log.value(), new Date());
            }else {
                //如果没有用户那么则认为登录失败
                String username =  (String) pjp.getArgs()[0];
                psLogs = new PsLogs(username, "", "登录但是失败了", new Date());
            }
            psLogsService.save(psLogs);
        }catch (Exception e){
            user =  (PsUser)session.getAttribute("user");
            //插入异常日志
            PsLogs psLogs = null;
            if(user != null){
                psLogs = new PsLogs(user.getUserCode(), user.getUserName(), log.value()+"出现了异常", new Date());

            }else {
                //如果没有用户那么则用户是在登录的时候出现了异常
                String username =  (String) pjp.getArgs()[0];
                psLogs = new PsLogs(username, "", "登录系统但是出现了异常", new Date());
            }
            psLogsService.save(psLogs);

            throw new RuntimeException(e);
        }

        return result;
    }

}
